<?php
namespace app\admin\model;

use app\common\model\CommonBase;
use app\common\service\Dynamic;
use app\admin\model\Baseinfo;
use app\admin\model\Valuation;
use app\admin\model\Chip;

class Securities extends Base
{
    protected $name = 'securities';
    const COMPANY = 'http://emweb.securities.eastmoney.com/PC_HSF10/CompanySurvey/CompanySurveyAjax?code=';
    const BUSINESS_RANK1 = 'http://emweb.securities.eastmoney.com/PC_HSF10/StockRelationship/StockRelationshipAjax?code=';
    const BUSINESS_RANK2 = '&orderBy=1&isAsc=false';
    const GOVERNMENT_BONDS = 2.83;
    const BACKGROUND_COLOR = '#FFFFFF';
    const BACKGROUND_COLOR_GOOD = '#FF5C5C';
    const STOCK_PRICE = 'http://qt.gtimg.cn/q=';

    protected $baseInfo;
    protected $analysis;
    protected $valuation;
    protected $shareholder;
    protected $shareholderinfo;
    protected $chip;
    protected $business;

    public function initialize(){

        $this->baseInfo = new Baseinfo();
        $this->analysis = new Analysis();
        $this->valuation = new Valuation();
        $this->shareholder= new Shareholder();
        $this->shareholderinfo = new Shareholderinfo();
        $this->chip = new Chip();
        $this->business = new Business();
    }

    public function securitieList($where=[]){

        $securitie = null;
        $where = ['sid'=>422];
        $securitie = self::where($where)->field('sid,stock_code,stock_name,jys,business_rank,status')->order('sid desc')->select();
        if(empty($securitie) || count($securitie) < 1){
            return [];
        }
        $securitie = collection($securitie)->toArray();
        foreach ($securitie AS &$v) {
            $v['score'] = 0;
            
            //当前价
            $price = Dynamic::Price($v['stock_code'], $v['jys']) ?? [];
            $v['price'] = $price['price'];
            $v['pe_ttm'] = $price['pe'];
            $v['pb'] = $price['pb'];
            if($v['pe_ttm'] > 0){
                if($v['pe_ttm'] < 5){
                    $v['pe_ttm_bj'] = '#FF5C5C';
                    $v['score'] += 1;
                }
            }else{
                $v['pe_ttm'] = '亏损';
            }
            //PB
            if($v['pb'] > 0){
                if($v['pb'] < 1){
                    $v['pb_bj'] = '#FF5C5C';
                    $v['score'] += 1;
                }
            }else{
                $v['pb'] = '亏损';
            }
            //筹码
            $v['chip_ratio'] = 0;
            $v['chip'] = $this->chip::getChip($v['sid'], $v['stock_code'], $v['jys']);
            if($v['chip'] > 0){
                $v['chip_ratio'] = substr(sprintf("%.3f",(($v['price']-$v['chip'])/$v['chip'])*100), 0,-1);
                if($v['chip_ratio'] <= 5){
                    $v['score'] += 1;
                    $v['chip_bj'] = '#FF5C5C';
                }
            }
            //股息
            $v['dividend_yield_ratio_bj'] = self::BACKGROUND_COLOR;
            $v['dividend_yield_ratio'] = $this->baseInfo::DividendYield($v['sid'],$v['stock_code'], $v['jys']) ?? 0;
            if($v['dividend_yield_ratio'] > 0){
                if($v['dividend_yield_ratio'] >= 6){
                    $v['score'] += 1;
                    $v['dividend_yield_ratio_bj'] = self::BACKGROUND_COLOR_GOOD;
                }
                $v['dividend_yield_ratio'].='%';
            }elseif($v['dividend_yield_ratio'] <= 0){
                $v['dividend_yield_ratio'].='亏损';
            }
            // p($v,1);
        }
        // p($securitie,1);
        return $securitie;
    }

    public function SecuritieInfo($data=[]){

        $this->where(['stock_code'=>$data['stock_code']])->find();
        $re = 1;
        $reId = $this->getCompanyInfo($data);
        $this->chip->addChip(['sid'=>$reId,'stock_code'=>$data['stock_code']]);
        $this->business->addBusiness(['sid'=>$reId,'stock_code'=>$data['stock_code']]);
        $this->baseInfo->getStockBaseInfo($data, $reId);
        $this->analysis->getStockBusinessAnalysis($data, $reId);
        $this->valuation->getStockValuation($data, $reId);
        $this->shareholder->crioShareholder($data, $reId);
        return $re;
    }

    //公司基本信息-公司概况
    protected function getCompanyInfo($data=[]){

        $company = file_get_contents(self::COMPANY.$data['jys'].$data['stock_code'].'&code='.$data['jys'].$data['stock_code']);
        $company = json_decode($company, true);

        $val = [];
        $val['stock_name'] = $company['jbzl']['agjc'];
        $val['institutions_name'] = $company['jbzl']['gsmc'];
        $val['institutions_industry'] = $company['jbzl']['sshy'];
        $val['region'] = $company['jbzl']['qy'];
        $val['address'] = $company['jbzl']['bgdz'];
        $val['reg_address'] = $company['jbzl']['zcdz'];
        $val['business'] = trim($company['jbzl']['jyfw']);
        $val['introduction'] = trim($company['jbzl']['gsjj']);
        $val['stock_type'] = 'Gp';
        $val['tradable_shares'] = '';
        $val['capital_stock'] = '';
        $val['tradable_shares'] = '';
        $val['pledge_proportion'] = '';
        $val['goodwill'] = '0';
        $val['note'] = '曾用名:'.trim($company['jbzl']['cym'])."<br>".'所属证监会行业:'.trim(($company['jbzl']['sszjhhy'])."<br>".'英文名称:'.trim($company['jbzl']['ywmc']));

        $stockBase = file_get_contents('https://gu.qq.com/'.$data['jys'].$data['stock_code'].'/gp');
        $val['turnover'] = 0;
        preg_match('/市销率:<\/span><span class="col-2-2 bl" data-reactid=".*?">(.*?)<\/span>/', $stockBase, $turnover);

        $val['current_ratio'] = file_get_contents('https://q.stock.sohu.com/cn/'.$data['stock_code'].'/cwzb.shtml');
        $current_encode = mb_detect_encoding($val['current_ratio'], array("ASCII","GB2312","GBK",'BIG5','UTF-8'));
        $val['current_ratio'] = mb_convert_encoding($val['current_ratio'], 'UTF-8', $current_encode);

        preg_match('/流动比率<\/th>.*\<td\>(.*)<\/td>/siU',$val['current_ratio'], $val['current_ratio']);
        $val['current_ratio'] = trim($val['current_ratio'][1]);

        $businessRank = '';
        $businessRank = file_get_contents(self::BUSINESS_RANK1.$data['jys'].$data['stock_code'].self::BUSINESS_RANK2);
        $businessRank = json_decode($businessRank, true);

        foreach ($businessRank['stockRandList'] AS  $brK=>$brV) {
            if($brV['gpdm']==$data['stock_code']){
                $val['business_rank'] = $brK;
            }
        }
        $reSecurities = self::where(['jys'=>$data['jys'], 'stock_code'=>$data['stock_code']])->find();
        if(!empty($reSecurities['sid'])){
            $val['updated_at'] = date('Y-m-d H:i:s');
            self::where(['sid'=>$reSecurities['sid']])->update($val);
            return $reSecurities['sid'];
        }else{
            $val['jys'] = $data['jys'];
            $val['stock_code'] = $data['stock_code'];
            return $this->insertGetId($val);
        }
    }

    //删除公司基本信息-公司概况
    public function delCompanyInfo($sid=0, $stock_code=''){

        $this->baseInfo->delStockBaseInfo($sid, $stock_code);
        $this->analysis->delStockBusinessAnalysis($sid, $stock_code);
        $this->valuation->delStockValuation($sid, $stock_code);
        $this->shareholder->delStockShareholder($sid, $stock_code);
        $this->shareholderinfo->delStockShareholderinfo($sid, $stock_code);
        $this->chip->delStockChip($sid, $stock_code);
        $this->business->delBusiness($sid, $stock_code);
        $this->where(['sid'=>$sid,'stock_code'=>$stock_code])->delete();
    }

    //详情-公司概况
    public function detailCompanyInfo($sid=0, $stock_code=''){

        $reVal = [];
        $reVal['companyInfo'] = $this->where(['sid'=>$sid,'stock_code'=>$stock_code])->find()->toArray();
        $reVal['stockBaseInfo'] = $this->baseInfo->detailStockBaseInfo($sid, $stock_code);

        if(!empty($reVal['stockBaseInfo']['gross_liability']) && is_numeric($reVal['stockBaseInfo']['gross_liability']) && !empty($reVal['stockBaseInfo']['monetary_assets']) && is_numeric($reVal['stockBaseInfo']['monetary_assets'])){

            $reVal['stockBaseInfo']['monetary_assets'] = floatval($reVal['stockBaseInfo']['monetary_assets']);
            if($reVal['stockBaseInfo']['monetary_assets']>0){
                $reVal['stockBaseInfo']['gross_liability'] = floatval($reVal['stockBaseInfo']['gross_liability']);
                $reVal['stockBaseInfo']['monetary_assets'] = sprintf("%.2f", $reVal['stockBaseInfo']['gross_liability']/$reVal['stockBaseInfo']['monetary_assets']);
            }
        }
        $reVal['stockBaseInfo']['net_assets_profit'] = !empty($reVal['stockBaseInfo']['net_assets_profit']) ? sprintf("%.2f",$reVal['stockBaseInfo']['net_assets_profit']).'%' : '' ;
        $reVal['stockBaseInfo']['asset_liability_ratio'] = !empty($reVal['stockBaseInfo']['asset_liability_ratio']) ? sprintf("%.2f",$reVal['stockBaseInfo']['asset_liability_ratio']).'%' : '' ;
        $reVal['stockBusinessAnalysis'] = $this->analysis->detailStockBusinessAnalysis($sid, $stock_code);
        $reVal['valuation'] = $this->valuation->detailValuation($sid, $stock_code);

        return $reVal;
    }

    //更新公司信息
    public function securitieInfoUpdate($sid=0, $stock_code='', $arr=[]){
        $this->where(['sid'=>$sid, 'stock_code'=>$stock_code])->update($arr);
        CommonBase::cClear();
    }

    //根据证券状态查询数据
    public function standbySe($where=[]){

        if(!isset($where['status'])){ return false;}
        $reSecuritiesList = [];
        $reSecuritiesList = $this->securitie->where($where)->order('sid desc')->field('sid, stock_code, stock_name,institutions_name, institutions_industry,price_earnings_ratio_ttm,jys,business_id,business_rank')->select();
        $time = date('Y',time());
        $time++;
        foreach($reSecuritiesList AS $staK=>$staV){

            $baseTmp = [];
            $baseTmp = $this->baseinfo->detailStockBaseInfo($staV['sid'], $staV['stock_code']);
            if(!empty($baseTmp['one_base_earnings']) && is_numeric($baseTmp['one_base_earnings'])){

                $valuationTmp = $this->valuationDb->where(['sid'=>$staV['sid'], 'stock_code'=>$staV['stock_code'], 'year'=>$time])->find();
                $ratio = 0.00;
                if(!empty($valuationTmp['ratio']) && is_numeric($valuationTmp['ratio'])){
                    $ratio = floatval($valuationTmp['ratio']);
                    if($ratio<=0){
                        $ratio = 0.00;
                    }
                }
                $liability_interest_rate = !empty($baseTmp['liability_interest_rate']) ? floatval($baseTmp['liability_interest_rate']) : self::GOVERNMENT_BONDS ;
                $intrinsic_value = $baseTmp['one_base_earnings']*(2*$ratio+8.5)*4.4/$liability_interest_rate;
                $intrinsic_value = sprintf("%.2f",$intrinsic_value);
                $intrinsic_value = $intrinsic_value;

                $reSecuritiesList[$staK]['ratio'] = $valuationTmp['ratio'].'%';
            }else{
                $intrinsic_value = '';
            }
            $reSecuritiesList[$staK]['gl_intrinsic'] = $intrinsic_value;
            if(is_numeric($staV['price_earnings_ratio_ttm']) && $ratio>0){
                $reSecuritiesList[$staK]['lq_peg'] = sprintf("%.2f",floatval($staV['price_earnings_ratio_ttm'])/$ratio);
            }else{
                $reSecuritiesList[$staK]['lq_peg'] = $staV['price_earnings_ratio_ttm'];
            }
            $staV['jys'] = mb_strtolower($staV['jys']);

            $tmpPrice = file_get_contents(self::STOCK_PRICE.$staV['jys'].$staV['stock_code']);
            $current_encode = mb_detect_encoding($tmpPrice, array("ASCII","GB2312","GBK",'BIG5','UTF-8'));
            $tmpPrice = mb_convert_encoding($tmpPrice, 'UTF-8', $current_encode);
            $baseTmp['price'] = explode('~',$tmpPrice)[3];

            $reSecuritiesList[$staK]['price'] = !empty($baseTmp['price']) ? floatval($baseTmp['price']) : 0 ;
            $reSecuritiesList[$staK]['cl'] = '1';
            if(!empty($reSecuritiesList[$staK]['gl_intrinsic']) && is_numeric($reSecuritiesList[$staK]['gl_intrinsic'])){
                $reSecuritiesList[$staK]['gl_intrinsic'] = floatval($reSecuritiesList[$staK]['gl_intrinsic']);
                $reSecuritiesList[$staK]['cl'] = $reSecuritiesList[$staK]['price']/$reSecuritiesList[$staK]['gl_intrinsic'];
                $reSecuritiesList[$staK]['cl'] = sprintf("%.2f", $reSecuritiesList[$staK]['cl']);
            }
        }
        return $reSecuritiesList;
    }
}